/**
 * Created by cuihongquan on 2015/7/6.
 * based on ztree, jqueryUI
 */
$.widget('summer.org', {
    version: '1.0',
    options: {
        'selectedMulti': true,
        'event': 'keyup',
        'url': 'demo.json',
        'tableUrl':'demo1.json',
        'idKey': 'oid',
        'pIdKey': 'pid',
        'rootId': '',
        'height': 450,
        'width': 600
    },
    //ztree的主要的配置
    _zTreeSettings: function () {
        var that = this;
        that._settings = {
            data: {
                simpleData: {
                    enable: true,
                    idKey: that.options.idKey,
                    pIdKey: that.options.pIdKey
                }
            },
            check: {
               // enable: that.options.selectedMulti,
                enable: false,
                chkStyle: "checkbox",
                radioType: 'all',
                chkboxType: { "Y": "s", "N": "s" },
                autoCheckTrigger: true
            },
            view: {
                selectedMulti: that.options.selectedMulti
            },
            callback: {
                onClick: function (e, treeId, node) {
                    that._zTreeOnClick(e, treeId, node);
                },
                onCheck: function (e, treeId, node) {
                    that._zTreeOnCheck(e, treeId, node);
                }
            }
        };
    },
    _create: function () {
        //构造组织机构树
        this._createOrg();
        //ztree的配置
        this._zTreeSettings();
        //绑定事件
        this._bindEvents();
    },
    destroy: function () {
        var ele = this.element,
            id = ele.attr('id'),
            $win = $('#' + id + 'Container'),
            $input = $win.find('.summer-org-tree-input');
        //input
        ele.off();
        //search
        $input.off();
        //关闭方法
        $win.find('.summer-window-close').off();
        //添加按钮
        $win.find('.summer-org-plus').off();
        //定义节点删除事件
        $win.find('.summer-org-selected-con').off();
        //删除dom
        $win.remove();
        //删除隐藏域
        $('#summer-org-'+id+'-data').remove();
        $('#'+id+'-hidden').remove();
    },

    //构建组织机构dom节点
    _createOrg: function () {
        var that = this,
            ele = this.element,
            id = ele.attr('id');
        //构建input隐藏域
        ele.after('<input type="hidden" id="' + id + '-hidden" value="" name="' + ele.attr('name') +
            '"><input type="hidden" id="summer-org-'+id+'-data">');
        //修改当前的input属性值
        ele.removeAttr('name');
        //构建window窗口里面的容器
        var $win = $('#' + id + 'Container');
        if ($win.length == 0) $(ele).closest('body').append('<div id="' + id + 'Container"></div>');
        $win = $('#' + id + 'Container');
        $win.append(
            //遮罩层
                '<div class="summer-window-mask" style="display: none"></div>' +
                //主容器
                '<div class="summer-window-container" style="width:' + that.options.width + 'px;height:' +
                that.options.height + 'px;left:50%;top:50%;margin-left:-' + that.options.width / 2 + 'px;' +
                'margin-top:-' + that.options.height / 2 + 'px;z-index:9999">' +
                //容器头
                '<div class="summer-window-header"><div class="summer-window-title"><i class="fa fa-laptop"></i>' +
                '行政区划</div><a class="summer-window-close" href="javascript:;"><i class="icon icon-wrong"></i></a></div>' +
                //容器内容
                '<div class="summer-window-body" style="width: 100%;height: 90%;">' +
                '<div class="summer-org"><div class="summer-org-search">' +
                '组织机构 <input type="text" class="summer-input summer-org-tree-input">' +
                '人员列表 <input type="text" class="summer-input summer-org-table-input"></div>' +
                '<div class="summer-org-treebox"><ul class="ztree" id="summer-org-tree-' + id + '"></ul></div>' +
                    '<div class="summer-org-table"></div>'+
                '<div class="summer-org-selected-con"></div></div></div>');
        if (that.options.selectedMulti) {
            $win.find('.summer-org').css('bottom', '50px').after(
                    '<div class="summer-org-plus">' +
                    '<a class="btn btn-primary btn-large" ' +
                    'href="javascript:;" class="summer-org-btn-plus"><span class="btn-i">' +
                    '<i class="icon icon-plus icon-white"></i></span>' +
                    '<span class="btn-word">添加</span></a></div>');
            //重新进行布局
            $win.find('.summer-org-treebox').css('bottom', '120px');
            $win.find('.summer-org-table').css('bottom', '120px');
        } else {
            $win.find('.summer-org-selected-con').hide();
        }
        $.ajax({
            url:that.options.tableUrl,
            type: 'POST',
            dataType:'json',
            async:false,
            success: function (data) {
                if (data.result === 'success' && data.data.length) {
                    var list = data.data;
                    window.localStorage.table = JSON.stringify(list);
                }
            },
            error:function(XMLResponse){alert(XMLResponse.responseText);}
        });
    },

    //加载数据
    _loadData: function (id) {
        var that = this;
        $.ajax({
            type: 'POST',
            data: {
                'id': that.options.rootId
            },
            async: true,
            url: that.options.url,
            success: function (data) {
                if (data.result === 'success' && data.data.length) {
                    var list = data.data;
                    window.localStorage.zzjg = JSON.stringify(list);
                    that._tree = $.fn.zTree.init($("#summer-org-tree-" + that.element.attr('id')), that._settings, list);
                    //展开一级节点
                    var nodes = that._tree.getNodes();
                    that._tree.expandNode(nodes[0], true, false, true);
                }
            }
        });
    },

    //绑定事件
    _bindEvents: function () {
        var that = this,
            ele = this.element,
            id = ele.attr('id'),
            $win = $('#' + id + 'Container'),
            $input = $win.find('.summer-org-tree-input'),
            $tableInput = $win.find('.summer-org-table-input'),
            $con = $win.find('.summer-org-selected-con'),
            $item,
            ids = [],
            names = [];

        //input框点击事件
        ele.on('click', null, function () {
            that._loadData(id);
            that._showWin($win);
        });

        //查询框的事件
        $input.on(that.options.event, null, function () {
            var nodes = that._tree.getNodesByFilter(
                //过滤方法
                function (node) {
                    var val = $win.find('.summer-org-tree-input').val().replace(/(^\s*)|(\s*$)/g, '');
                    return (val && node.name.match(val));
                }, false);
            if (that.options.selectedMulti) {
                //取得这个node集合
                if (nodes.length) {
                    that._tree.selectNode(nodes[0]);
                    that._zTreeOnClick(null, null, nodes[0]);
                }
            } else {
                if (nodes.length) that._tree.selectNode(nodes[0]);
            }
            //$(this).focus();
        });

        $tableInput.on(that.options.event,null,function(){
            var val = $win.find('.summer-org-table-input').val().replace(/(^\s*)|(\s*$)/g, ''),
                $table = $win.find('.summer-org-table'),
                $items = $table.find('.summer-org-table-item');
            $('.summer-org-searched').removeClass('summer-org-searched');
            $.each($items,function(index,value){
                if(val && value.innerHTML.match(val)){
                    $(this).addClass('summer-org-searched');
                }
            });
        });

        //关闭方法
        $win.find('.summer-window-close').on('click', null, function () {
            that._closeWin($win);
        });

        //添加按钮
        $win.find('.summer-org-plus').on('click', null, function () {
           /* that._resetInput($win);*/
            $item = $con.find('.summer-org-selected-item');
            ids = [];
            names = [];
            $.each($item, function (index, item) {
                ids.push(item.id);
                names.push($(item).text());
            });
            that._setValues(that,ids.join(),names.join());

        });

        //定义节点删除事件
        $con.on('click', '.summer-org-selected-item', function () {
            $(this).remove();
        });

        $win.find('.summer-org-table').on('click','.summer-org-table-item',function(){
            var t = this,id = t.getAttribute('data-id'),
                flag = true;
            $item = $con.find('.summer-org-selected-item');
            if($item.length){
                $.each($item, function (index, item) {
                    if (item.id === id) {
                        flag = false;
                    }
                });
            }
            if (flag) {
                $con.append('<span class="summer-org-selected-item" id="' + id +
                    '">' + this.innerHTML + '<span class="icon icon-wrong"></span></span>');
            }
        });
    },

    //树的check事件
    _zTreeOnCheck: function (e, treeId, node) {
        this._zTreeOnClick(e, treeId, node);
    },

    //树的点击事件
    _zTreeOnClick: function (e, treeId, node) {
        var that = this,
            ele = that.element,
            $win = $('#' + ele.attr('id') + 'Container'),
          // $con = $win.find('.summer-org-selected-con'),
            //$item = $con.find('.summer-org-selected-item'),
            $table = $win.find('.summer-org-table');
        $.ajax({
            url:that.options.tableUrl,
            type: 'POST',
            dataType:'json',
            data: {
                'id': node.code
            },
            success: function (data) {
                if (data.result === 'success' && data.data.length) {
                    var list = data.data,
                        arr=[];
                    window.localStorage.table = JSON.stringify(list);
                    $.each(list,function(index,value){
                        arr.push('<span class="summer-org-table-item" title="'+value.name+'" style="overflow:hidden;width:95%;whith-space:nowrap;text-overflow:ellipsis;display:inline-block" data-id="'+value.id+'">'+value.name+'</span>');
                    });
                    $table.empty().append(arr.join(' '));
                }else if(data.result === 'success'){
                    $table.empty().append('');
                }
            },
            error:function(XMLResponse){alert(XMLResponse.responseText);}
        });

        /*var that = this,
            ele = that.element,
            id= ele.attr('id'),
            $win = $('#' + id + 'Container'),
            $con = $win.find('.summer-org-selected-con'),
            $item = $con.find('.summer-org-selected-item'),
            flag = true;
        //如果是多选的话
        if (that.options.selectedMulti) {
            //点击事件同时事添加check
            that._tree.checkNode(node, true, false);
            //如果存在数据
            $.each($item, function (index, item) {
                if (item.id === node[that._settings.data.simpleData.idKey]) {
                    flag = false;
                }
            });
            if (flag) {
                $con.append('<span class="summer-org-selected-item" id="' + node[that._settings.data.simpleData.idKey] +
                    '">' + node.name + '<span class="icon icon-wrong"></span></span>');
            }
            //清空查询框并继续添加
            $win.find('.summer-org-tree-input').val('');
        } else {
            that._setValue(that,node);
        }*/
    },

    //窗口关闭事件
    _closeWin: function ($win) {
        $win.find('.summer-window-mask').hide();
        $win.find('.summer-window-container').removeClass('transition-in');
    },

    //窗口关闭事件
    _showWin: function ($win) {
        this._resetInput();
        $win.find('.summer-window-mask').show();
        $win.find('.summer-window-container').addClass('transition-in');
    },

    //单选赋值方法
    _setValue:function(that,node){
        var ele = that.element,
            id = ele.attr('id');
        $('#'+id+'-hidden').val(node[that._settings.data.simpleData.idKey]);
        $('#summer-org-'+id+'-data').attr({
            'data-ids':node[that._settings.data.simpleData.idKey],
            'data-names':node.name
        });
        ele.val(node.name);
        that._closeWin($('#' + id + 'Container'));
    },

    //多选赋值方法
    _setValues :function(that,ids,names){
        var ele = that.element,
            id = ele.attr('id');
        $('#summer-org-'+id+'-data').attr({
            'data-ids':ids,
            'data-names':names
        });
        $('#'+id+'-hidden').val(ids);
        that._closeWin($('#' + id + 'Container'));
        ele.val(names);
    },
    //赋值方法 接字符串
    setValues:function(ids){
        var that = this,
            //opts = that.options,
            idsArr = ids.split(',');
            nodeList = [],
            names=[];
        if(window.localStorage.table){
            nodeList = JSON.parse(window.localStorage.table);
        }else{
            $.error('window.localStorage.zzjg is empty!!');
        }
        $.each(idsArr,function(index,value){
            $.each(nodeList,function(j,w){
                if(value== w.id){
                   names.push(w.name);
                }
            });
        });
        //调用私有的方法
        that._setValues(that,ids,names);
    },

    //重置方法
    _resetInput: function () {
        var that = this,
            ele = that.element,
            id = ele.attr('id');
        $('#summer-org-'+id+'-data').attr({
            'data-ids':'',
            'data-names':''
        });
        $('#'+id+'-hidden').val('');
        ele.val('');
        $('#'+id+'Container').find('.summer-org-selected-con').empty();
    }
});